import 'package:dio/dio.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'flutter_global_monitoring_utils.dart';

enum VgHttpType{
  get,
  post,
}

extension VgHttpTypeExtension on VgHttpType{
  ///获取请求类型
  String getRequestMethod(){
    if(this == null){
      return null;
    }
    switch(this){
      case VgHttpType.get:
        return HttpUtils.GET;
      case VgHttpType.post:
        return HttpUtils.POST;
    }
    return null;
  }
}

///简单提取公共请求类
class VgHttpUtils {
  /// 网络错误提示语
  static const String _NET_ERROR_HINT = "网络连接不可用";

  // /// 身份过期服务器返回的提示语
  // static const String IDENTITY_OUT_DATE = "身份信息过期";

  /// 后台返回数据为空
  static const String _NET_DATA_NULL_ERROR = "后台数据错误";

  /// 请求超时
  static const String _NET_TIME_OUT = "网络请求超时";

  ///5秒超时
  static const int _TIME_OUT_FIVE_THOUSAND = 5000;

  ///10秒超时
  static const int _TIME_OUT_TEN_THOUSAND = 15000;

  ///GET请求成功后回调未转义map
  static Future<VgHttpResponse> get(
    String url, {
    int millisecondsTimeOut = _TIME_OUT_TEN_THOUSAND,
    Map<String, dynamic> params,
    BaseCallback callback,
  }) {
    assert(millisecondsTimeOut != null ? (millisecondsTimeOut > 0) : true,
        "time out must greater than 0");
    if (StringUtils.isEmpty(url)) {
      callback?.onError("请求接口url为空");
      return null;
    }
    Future<VgHttpResponse> resultFuture =
        HttpUtils.get(url: url, query: params);

    Future _local = resultFuture.then((resp) {
      BaseResponseBean bean = BaseResponseBean.fromMap(resp?.data);
      if (bean == null) {
        callback?.onError(_NET_DATA_NULL_ERROR);
        return;
      }
      if (bean.success) {
        callback?.onSuccess(resp?.data);
      } else {
        if(bean?.code!="610"){
          callback?.onError(bean.msg);
        }
      }
    }).timeout(Duration(milliseconds: millisecondsTimeOut), onTimeout: () {
      print("\n"
          "------------------------------------------------------------------"
          "\n\n"
          "  VgHttpUtils--异常：\n >>>>>>请求方式：GET\n >>>>>>路径：${url ?? ""} 接口\n >>>>>>参数：${params?.toString() ?? ""}\n >>>>>>请求超时}"
          "\n\n"
          "------------------------------------------------------------------");
      callback?.onError(_NET_TIME_OUT);
    });
    if(ConstantRepository.of().isCatchHttpError()){
      _local.catchError((error) {
        print("\n"
            "------------------------------------------------------------------"
            "\n\n"
            "  VgHttpUtils--异常：\n >>>>>>请求方式：GET\n >>>>>>路径：${url ?? ""} 接口\n >>>>>>参数：${params?.toString() ?? ""} \n >>>>>>${error.toString()}"
            "\n\n"
            "------------------------------------------------------------------");
        callback?.onError(_NET_ERROR_HINT);
      });
    }
    return resultFuture;
  }

  ///POST请求成功后回调未转义map
  static void post(String url,
      {Map<String, dynamic> params,
      BaseCallback callback,
      dynamic body,
      int millisecondsTimeOut = _TIME_OUT_TEN_THOUSAND}) {
    assert(millisecondsTimeOut != null ? (millisecondsTimeOut > 0) : true,
        "time out must greater than 0");
    if (StringUtils.isEmpty(url)) {
      callback?.onError("请求接口url为空");
      return;
    }
    Future netHttp;
    if (body == null || body.isEmpty) {
      netHttp = HttpUtils.post(url: url, query: params);
    } else {
      netHttp = HttpUtils.post(
          url: url,
          query: params,
          body: (body is Map) ? FormData.fromMap(body) : body);
    }
    netHttp?.then((resp) {
      BaseResponseBean bean = BaseResponseBean.fromMap(resp?.data);
      if (bean == null) {
        callback?.onError(_NET_DATA_NULL_ERROR);
        return;
      }
      if (bean.success) {
        callback?.onSuccess(resp?.data);
      } else {
        if(bean?.code!="610"){
          callback?.onError(bean.msg);
        }
      }
    })?.catchError((error) {
      try {
        print("\n"
            "------------------------------------------------------------------"
            "\n\n"
            "  VgHttpUtils--异常：\n >>>>>>请求方式：POST\n >>>>>>路径：${url ?? "空接口"} 接口\n >>>>>>参数：${params?.toString() ?? body?.toString()}\n >>>>>>请求超时}"
            "\n\n"
            "------------------------------------------------------------------");
      } catch (e) {}
      callback?.onError(_NET_ERROR_HINT);
    })?.timeout(Duration(milliseconds: millisecondsTimeOut), onTimeout: () {
      try {
        print("\n"
            "------------------------------------------------------------------"
            "\n\n"
            "  VgHttpUtils--异常：\n >>>>>>请求方式：POST\n >>>>>>路径：${url ?? "空接口"} 接口\n >>>>>>参数：${params?.toString() ?? body?.toString()}\n >>>>>>请求超时}"
            "\n\n"
            "------------------------------------------------------------------");
      } catch (e) {}
      callback?.onError(_NET_TIME_OUT);
    });
  }
}

/// success : true
/// code : "200"
/// msg : "处理成功"
/// data : null
/// extra : null

class BaseResponseBean {
  bool success;
  String code;
  String msg;
  dynamic data;
  dynamic extra;

  static BaseResponseBean fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    BaseResponseBean baseResponseBeanBean = BaseResponseBean();
    baseResponseBeanBean.success = map['success'];
    baseResponseBeanBean.code = map['code'];
    baseResponseBeanBean.msg = map['msg'];
    baseResponseBeanBean.data = map['data'];
    baseResponseBeanBean.extra = map['extra'];
    return baseResponseBeanBean;
  }

  Map toJson() => {
        "success": success,
        "code": code,
        "msg": msg,
        "data": data,
        "extra": extra,
      };
}



// ///获取顶部信息请求
// void getTopInfoHttp(){
//   VgHttpUtils.get(INDEX_TOP_INFO_API,params: {
//     "authId":UserRepository.getInstance().authId ?? "",
//     "companyid": UserRepository.getInstance().companyId ?? "",
//   },callback: BaseCallback(
//       onSuccess: (val){
//         IndexTopInfoResponseBean bean = IndexTopInfoResponseBean.fromMap(val);
//         topInfoValueNotifier?.value = bean?.data;
//       },
//       onError: (msg){
//         VgToastUtils.toast(AppMain.context, msg);
//       }
//   ));
// }